package com.luotao.test.hbase.domain;

import com.luotao.devp.base.test.TesterConcurrent;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-28
 * Time: 16:47
 */
public class ExampleClient {
    public static void main(String[] args) throws IOException {
        Configuration config = HBaseConfiguration.create();

        HBaseAdmin admin = new HBaseAdmin(config);
        HTableDescriptor htd = new HTableDescriptor("test4");
        HColumnDescriptor hcd = new HColumnDescriptor("data");
        htd.addFamily(hcd);
        admin.createTable(htd);

        byte[] tablename = htd.getName();

        HTableDescriptor[] tables = admin.listTables();
        if (tables.length != 1 && Bytes.equals(tablename, tables[0].getName())) {
            throw new IOException("Failed create of table");
        }

        final HTable table = new HTable(config, tablename);
        long cost = TesterConcurrent.runLoopInner(10, new TesterConcurrent.ITestable() {
            @Override
            public void execute(long index, long threadid, int loop_index) throws Exception {
                byte[] row1 = Bytes.toBytes("row" + index);

                Put p1 = new Put(row1);
                byte[] databytes = Bytes.toBytes("data");

                p1.add(databytes, Bytes.toBytes("1"), Bytes.toBytes("value1"));
                table.put(p1);
                Get g = new Get(row1);
                Result result = table.get(g);
                System.out.println("Get: " + result);
                Scan scan = new Scan();

//                ResultScanner scanner = table.getScanner(scan);
//
//                try {
//                    for (Result scannerResult : scanner) {
//                        System.out.println("Scan: " + scannerResult);
//                    }
//                } finally {
//                    scanner.close();
//                }
            }
        }, 1);
        System.out.println("cost = " + cost);
        admin.disableTable(tablename);
        admin.deleteTable(tablename);
    }
}
